package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.User;
import com.util.DBHelp;
import com.util.RowMapper;

public class UserDao {
	private DBHelp<User> db=new DBHelp<User>();
	
	public User findByName(String name){
		String sql="select id,username,`password`,image from t_user where username=?";
		return db.executeQueryForObject(sql, new UserRowMapper(),name);
	}
	public User findByUserId(String userid){
		String sql="select id,username,`password`,image from t_user where id=?";
		return db.executeQueryForObject(sql, new UserRowMapper(),userid);
	}
	public List<User> findAll() {
		final String sql = "select id,username,'password',image from t_user";
		return db.executeQueryForList(sql, new UserRowMapper());
	}
	
	private class UserRowMapper implements RowMapper<User>{

		public User mapRow(ResultSet rs) throws SQLException {
			User u=new User();
			u.setId(rs.getString("id"));
			u.setImage(rs.getString("image"));
			u.setPassword(rs.getString("password"));
			u.setUserName(rs.getString("username"));
			return u;
		}
	}

	public void save(User user) {
		// TODO Auto-generated method stub
		String sql="INSERT INTO t_user(id,username,password,image) values (?,?,?,?) ";
		db.executeSQL(sql, user.getId(),user.getUserName(),user.getPassword(),user.getImage());
	}
	public void update(User u) {
		// TODO Auto-generated method stub
		String sql="update t_user set username=? password=? image=? where id=?";
		db.executeSQL(sql, u.getUserName(),u.getPassword(),u.getImage(),u.getId());
	}

}
